package jnpf.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.entity.VisualdevEntity;
import jnpf.base.service.VisualdevService;
import jnpf.base.util.DynDicUtil;
import jnpf.base.util.VisualUtils;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.emnus.FileTypeEnum;
import jnpf.engine.entity.FlowTaskEntity;
import jnpf.engine.service.FlowTaskService;
import jnpf.entity.ZXGL_LiXiangGuanLiEntity;
import jnpf.entity.ZXGL_XMCFZGBMJSEntity;
import jnpf.entity.ZXGL_XMCFZGBMJS_MingXiEntity;
import jnpf.entity.ZXGL_XiangMuLiXiang_MingXiEntity;
import jnpf.exception.DataException;
import jnpf.exception.WorkFlowException;
import jnpf.file.FileApi;
import jnpf.generater.util.GeneraterSwapUtil;
import jnpf.model.common.ZXGL_Leaders;
import jnpf.model.common.ZXGL_XzbmLeaders;
import jnpf.model.common.ZXGL_ZzbmLeaders;
import jnpf.model.zxgl_lixiangguanli.*;
import jnpf.model.zxgl_xmcfzgbmjs.ZXGL_XMCFZGBMJSCrForm;
import jnpf.model.zxgl_xmcfzgbmjs.ZXGL_XMCFZGBMJS_MingXiModel;
import jnpf.permission.OrganizeApi;
import jnpf.permission.entity.OrganizeEntity;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.model.user.UserInfoVO;
import jnpf.permission.service.UserService;
import jnpf.service.*;
import jnpf.util.*;
import jnpf.util.context.SpringContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.FileNameUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ZXGL_LiXiangGuanLi
 *
 * @版本： V2.0
 * @版权： 河北交投智能交通技术有限责任公司
 * @作者： 数字交投项目组
 * @日期： 2025-03-17
 */
@Slf4j
@RestController
@Api(tags = "立项管理", value = "zxgl")
@RequestMapping("/ZXGL_LiXiangGuanLi")
public class ZXGL_LiXiangGuanLiController {

    private static final Logger logger = LoggerFactory.getLogger(ZXGL_LiXiangGuanLiController.class);

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private ZXGL_LiXiangGuanLiService zXGL_LiXiangGuanLiService;

    @Autowired
    private ZXGL_XiangMuLiXiang_MingXiService zXGL_XiangMuLiXiang_MingXiService;


    @Autowired
    private ZXGL_XMCFZGBMJSService zXGL_XMCFZGBMJSService;

    @Autowired
    private ZXGL_XMCFZGBMJS_MingXiService zXGL_XMCFZGBMJS_MingXiService;

    @Autowired
    private OrganizeApi organizeApi;

    @Autowired
    private ZXGl_DictionarydataService zxgl_dictionarydataService;

    @Autowired
    private ZXGL_LiXiangGuanLiXiaLaKuangService zxgl_liXiangGuanLiXiaLaKuangService;

    @Autowired
    private VisualdevService visualdevService;

    @Autowired
    private DynDicUtil dynDicUtil;

    @Autowired
    private UserService userService;

//    @DubboReference
//    private FileUploadProvider fileUploadProvider;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @Autowired
    private FlowTaskService flowTaskService;

    @Autowired
    private ZXGL_OrganizeService zxglOrganizeService;

    /**
     * 列表
     *
     * @param zXGL_LiXiangGuanLiPagination
     * @return
     */
    @ApiOperation("立项管理分页")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ZXGL_LiXiangGuanLiPagination zXGL_LiXiangGuanLiPagination) throws IOException {
        log.info("zXGL_LiXiangGuanLiPagination" + zXGL_LiXiangGuanLiPagination);
        List<ZXGL_LiXiangGuanLiEntity> list = zXGL_LiXiangGuanLiService.getList(zXGL_LiXiangGuanLiPagination);
        //处理id字段转名称，若无需转或者为空可删除
        for (ZXGL_LiXiangGuanLiEntity entity : list) {
            entity.setOrganizeName(generaterSwapUtil.comSelectValues(entity.getOrganizeName()));
            entity.setDepartmentName(generaterSwapUtil.comSelectValues(entity.getDepartmentName()));
            entity.setCreatorUser(generaterSwapUtil.userSelectValues(entity.getCreatorUser()));
            entity.setScfj(generaterSwapUtil.getFileNameInJson(entity.getScfj()));
        }
        List<ZXGL_LiXiangGuanLiListVO> listVO = JsonUtil.getJsonToList(list, ZXGL_LiXiangGuanLiListVO.class);
        for (ZXGL_LiXiangGuanLiListVO zXGL_LiXiangGuanLiVO : listVO) {
        }


        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(zXGL_LiXiangGuanLiPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }


    /**
     * 创建
     *
     * @param zXGL_LiXiangGuanLiCrForm
     * @return
     */
    @ApiOperation("立项管理添加")
    @PostMapping
    @Transactional
    public ActionResult create(@RequestBody @Valid ZXGL_LiXiangGuanLiCrForm zXGL_LiXiangGuanLiCrForm) throws DataException {
        String token = UserProvider.getAuthorize();

        // region 注释
        //        String jsonString = JSON.toJSONString(zXGL_LiXiangGuanLiCrForm);
        //        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        //        logger.info("项目立项数据：{}----------->" + jsonObject.toJSONString());
        //        String mainId = RandomUtil.uuId();
        //        //  UserInfo userInfo = userProvider.get();
        //        ZXGL_LiXiangGuanLiEntity entity = JsonUtil.getJsonToBean(zXGL_LiXiangGuanLiCrForm, ZXGL_LiXiangGuanLiEntity.class);
        //        entity.setId(mainId);
        //        // entity.setCreatorTime(new Date());
        //        zXGL_LiXiangGuanLiService.save(entity);
        //        List<ZXGL_XiangMuLiXiang_MingXiEntity> ZXGL_XiangMuLiXiang_MingXiList = JsonUtil.getJsonToList(zXGL_LiXiangGuanLiCrForm.getZxgl_xiangmulixiang_mingxiList(), ZXGL_XiangMuLiXiang_MingXiEntity.class);
        //
        //        Map<String, List<ZXGL_XiangMuLiXiang_MingXiEntity>> map2 = new HashMap<>();
        //        List<ZXGL_XiangMuLiXiang_MingXiEntity> list = new ArrayList<>();
        //
        //        for (ZXGL_XiangMuLiXiang_MingXiEntity entitys : ZXGL_XiangMuLiXiang_MingXiList) {
        //            entitys.setId(RandomUtil.uuId());
        //            entitys.setMainid(entity.getId());
        //            entitys.setCreatorTime(new Date());
        //            zXGL_XiangMuLiXiang_MingXiService.save(entitys);
        //            //遍历部门信息，根据主责部门循环，创建明细内容
        //            list.add(entitys);
        //        }
        //
        //        String flag = "";
        //        ObjectMapper objectMapper = new ObjectMapper();
        //        try {
        //            JsonNode rootNode = objectMapper.readTree(jsonObject.toJSONString());
        //            JsonNode listNode = rootNode.get("zxgl_xiangmulixiang_mingxiList");
        //            if (listNode != null && listNode.isArray()) {
        //                for (JsonNode item : listNode) {
        //                    if (item.has("zzbm")) {
        //                        flag = "1";
        //                        logger.info("存在 'zzbm' 字段");
        //                    }
        //                }
        //            }
        //        } catch (IOException e) {
        //            e.printStackTrace();
        //        }
        //        logger.info("不存在 'zzbm' 字段");
        //        if ("1".equals(flag) && "1".equals(jsonObject.getString("sftj"))) {
        //
        //            map2 = groupingArrayListTwo(list);
        //            //遍历分组后的map2
        //            for (String s : map2.keySet()) {
        //                logger.info("分组之后：{}---->" + map2.get(s));
        //                logger.info("分组之后个数：{}---->" + map2.get(s).size());
        //                ZXGL_XMCFZGBMJSEntity zxgl_xmcfzgbmjsEntity = new ZXGL_XMCFZGBMJSEntity();
        //                ZXGL_XMCFZGBMJSCrForm zXGL_XMCFZGBMJSCrForm = new ZXGL_XMCFZGBMJSCrForm();
        //                String zhujianID = RandomUtil.uuId();
        //                zxgl_xmcfzgbmjsEntity.setId(zhujianID);
        //                zxgl_xmcfzgbmjsEntity.setXmlxdid(mainId);
        //                zXGL_XMCFZGBMJSCrForm.setXmlxdid(mainId);
        //
        ////                zxgl_xmcfzgbmjsEntity.setCreatorTime(new Date());
        ////                zXGL_XMCFZGBMJSCrForm.setCreatorTime(System.currentTimeMillis());
        //
        //
        //                logger.info("部门信息：{}---->" + map2.get(s).get(0).getZzbm());
        //
        //                String managerId = organizeApi.getById(map2.get(s).get(0).getZzbm()).getManager();
        //                logger.info("managerId:{}--->" + managerId);
        //
        //                String Id = organizeApi.getById(map2.get(s).get(0).getZzbm()).getId();
        //                logger.info("Id:{}--->" + Id);
        //
        //                UserInfo userInfo = userProvider.get();
        //
        //
        //                zxgl_xmcfzgbmjsEntity.setDepartmentName(map2.get(s).get(0).getZzbm());
        //                zXGL_XMCFZGBMJSCrForm.setDepartmentName(map2.get(s).get(0).getZzbm());
        //                zxgl_xmcfzgbmjsEntity.setOrganizeName(zXGL_LiXiangGuanLiCrForm.getOrganizeName());
        //                zXGL_XMCFZGBMJSCrForm.setOrganizeName(zXGL_LiXiangGuanLiCrForm.getOrganizeName());
        ////                zxgl_xmcfzgbmjsEntity.setZrr(map2.get(s).get(0).getZzr());
        //                zxgl_xmcfzgbmjsEntity.setCreatorTime(entity.getCreatorTime());
        //                zXGL_XMCFZGBMJSCrForm.setCreatorTime(entity.getCreatorTime().getTime());
        //                zxgl_xmcfzgbmjsEntity.setLxwj(zXGL_LiXiangGuanLiCrForm.getScfj());
        //                zXGL_XMCFZGBMJSCrForm.setLxwj(zXGL_LiXiangGuanLiCrForm.getScfj());
        //                zxgl_xmcfzgbmjsEntity.setBt(zXGL_LiXiangGuanLiCrForm.getBt());
        //                zXGL_XMCFZGBMJSCrForm.setBt(zXGL_LiXiangGuanLiCrForm.getBt());
        //
        //
        //                OrganizeEntity organizeEntity = organizeApi.getById(entity.getDepartmentName());
        //                logger.info("组织信息：{}------>" + JSON.toJSONString(organizeEntity));
        //                zxgl_xmcfzgbmjsEntity.setZrr(organizeEntity.getManager());
        //                zXGL_XMCFZGBMJSCrForm.setZrr(organizeEntity.getManager());
        //                zXGL_XMCFZGBMJSService.save(zxgl_xmcfzgbmjsEntity);
        //
        //                List<ZXGL_XMCFZGBMJS_MingXiModel> zxgl_xmcfzgbmjs_mingXiEntityList = new ArrayList<>();
        //                List<ZXGL_XMCFZGBMJS_MingXiEntity> zxgl_xmcfzgbmjs_mingXiEntityList1 = new ArrayList<>();
        //                //操作
        //                for (int i = 0; i < map2.get(s).size(); i++) {
        //                    ZXGL_XMCFZGBMJS_MingXiModel zxgl_xmcfzgbmjs_mingXiModel = new ZXGL_XMCFZGBMJS_MingXiModel();
        //                    ZXGL_XMCFZGBMJS_MingXiEntity zxgl_xmcfzgbmjs_mingXiEntity = new ZXGL_XMCFZGBMJS_MingXiEntity();
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setId(RandomUtil.uuId());
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setMainid(zxgl_xmcfzgbmjsEntity.getId());
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setCreatorTime(new Date());
        //                    // zxgl_xmcfzgbmjs_mingXiModel.setCreatorTime(System.currentTimeMillis());
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setXmid(map2.get(s).get(i).getId());
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setXmmc(map2.get(s).get(i).getXmmc());
        //                    zxgl_xmcfzgbmjs_mingXiModel.setXmmc(map2.get(s).get(i).getXmmc());
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setXmbh(map2.get(s).get(i).getXmbh());
        //                    zxgl_xmcfzgbmjs_mingXiModel.setXmbh(map2.get(s).get(i).getXmbh());
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setXmlx(map2.get(s).get(i).getXmlx());
        //                    zxgl_xmcfzgbmjs_mingXiModel.setXmlx(map2.get(s).get(i).getXmlx());
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setXmly(map2.get(s).get(i).getXmly());
        //                    zxgl_xmcfzgbmjs_mingXiModel.setXmly(map2.get(s).get(i).getXmly());
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setJhksrq(map2.get(s).get(i).getJhkssj());
        //                    if (map2.get(s).get(i).getJhkssj() != null) {
        //                        zxgl_xmcfzgbmjs_mingXiModel.setJhksrq(map2.get(s).get(i).getJhkssj().getTime());
        //                    }
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setJhjsrq(map2.get(s).get(i).getJhjssj());
        //                    if (map2.get(s).get(i).getJhjssj() != null) {
        //                        zxgl_xmcfzgbmjs_mingXiModel.setJhjsrq(map2.get(s).get(i).getJhjssj().getTime());
        //                    }
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setZrbm(map2.get(s).get(i).getZzbm());
        //                    zxgl_xmcfzgbmjs_mingXiModel.setZrbm(map2.get(s).get(i).getZzbm());
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setXzbm(map2.get(s).get(i).getXzbm());
        //                    zxgl_xmcfzgbmjs_mingXiModel.setXzbm(map2.get(s).get(i).getXzbm());
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setMblx(map2.get(s).get(i).getMblx());
        //                    zxgl_xmcfzgbmjs_mingXiModel.setMblx(map2.get(s).get(i).getMblx());
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setMbz(map2.get(s).get(i).getMbz());
        //                    zxgl_xmcfzgbmjs_mingXiModel.setMbz(map2.get(s).get(i).getMbz());
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setGzmb(map2.get(s).get(i).getGzmb());
        //                    zxgl_xmcfzgbmjs_mingXiModel.setGzmb(map2.get(s).get(i).getGzmb());
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setFkzq(map2.get(s).get(i).getFkzq());
        //                    zxgl_xmcfzgbmjs_mingXiModel.setFkzq(map2.get(s).get(i).getFkzq());
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntity.setMbzdw(map2.get(s).get(i).getMbzdw());
        //                    zxgl_xmcfzgbmjs_mingXiModel.setMbzdw(map2.get(s).get(i).getMbzdw());
        //
        //
        //                    zxgl_xmcfzgbmjs_mingXiEntityList.add(zxgl_xmcfzgbmjs_mingXiModel);
        //                    String toJSONString = JSON.toJSONString(zxgl_xmcfzgbmjs_mingXiEntity);
        //                    logger.info("项目分解到部门toJSONString:{}--------->" + JSONObject.parseObject(toJSONString));
        //                    zxgl_xmcfzgbmjs_mingXiEntityList1.add(zxgl_xmcfzgbmjs_mingXiEntity);
        ////                    zXGL_XMCFZGBMJS_MingXiService.saveBatch(zxgl_xmcfzgbmjs_mingXiEntity);
        //                }
        //
        //                logger.info("保存明细数据：{}----->" + zxgl_xmcfzgbmjs_mingXiEntityList1.toString());
        //                logger.info("zxgl_xmcfzgbmjs_mingXiEntityList:{}----->" + zxgl_xmcfzgbmjs_mingXiEntityList.toString());
        //                zXGL_XMCFZGBMJS_MingXiService.saveBatch(zxgl_xmcfzgbmjs_mingXiEntityList1);
        //                zXGL_XMCFZGBMJSCrForm.setZxgl_xmcfzgbmjs_mingxiList(zxgl_xmcfzgbmjs_mingXiEntityList);
        //                String visualId = "667650650904992965";
        //                VisualdevEntity visualdevEntity = visualdevService.getInfo(visualId);
        //
        //                try {
        //                    VisualUtils.submitFlowTask(visualdevEntity, zhujianID, zXGL_XMCFZGBMJSCrForm, userInfo, zXGL_XMCFZGBMJSCrForm.getCandidateList());
        //                    FlowTaskEntity flowTaskEntity = flowTaskService.getInfo(zhujianID);
        //                    if (flowTaskEntity != null) {
        //                        flowTaskEntity.setTitle(zXGL_XMCFZGBMJSCrForm.getBt());
        //                        flowTaskService.update(flowTaskEntity);
        //                    }
        //                } catch (WorkFlowException e) {
        //                    e.printStackTrace();
        //                }
        //            }
        //        }
        // endregion

        String mainId = RandomUtil.uuId();
        //  UserInfo userInfo = userProvider.get();
        ZXGL_LiXiangGuanLiEntity entity = JsonUtil.getJsonToBean(zXGL_LiXiangGuanLiCrForm, ZXGL_LiXiangGuanLiEntity.class);

        // region 主表赋值部门负责人和部门领导
        ZXGL_Leaders leaders = zxglOrganizeService.getLeaders();
        entity.setDepartmentManager(leaders.getDepartmentManager());
        entity.setDepartmentHeadleader(leaders.getDepartmentHeadleader());
        // endregion
        entity.setId(mainId);
        // entity.setCreatorTime(new Date());
        boolean save = zXGL_LiXiangGuanLiService.save(entity);
        if (save) {
            String flag = "";
            if (zXGL_LiXiangGuanLiCrForm.getZxgl_xiangmulixiang_mingxiList() != null && zXGL_LiXiangGuanLiCrForm.getZxgl_xiangmulixiang_mingxiList().size() > 0) {
                List<ZXGL_XiangMuLiXiang_MingXiEntity> ZXGL_XiangMuLiXiang_MingXiList = JsonUtil.getJsonToList(zXGL_LiXiangGuanLiCrForm.getZxgl_xiangmulixiang_mingxiList(), ZXGL_XiangMuLiXiang_MingXiEntity.class);
                // region 保存立项管理明细表信息
                List<ZXGL_XiangMuLiXiang_MingXiEntity> list = new ArrayList<>();
                for (ZXGL_XiangMuLiXiang_MingXiEntity entitys : ZXGL_XiangMuLiXiang_MingXiList) {
                    entitys.setId(RandomUtil.uuId());
                    entitys.setMainid(entity.getId());
                    entitys.setCreatorTime(new Date());

                    // region 子表赋值部门负责人和部门领导
                    entitys.setDepartmentManager(leaders.getDepartmentManager());
                    entitys.setDepartmentHeadleader(leaders.getDepartmentHeadleader());
                    // endregion

                    // region 子表赋值主责部门负责人和部门领导
                    ZXGL_ZzbmLeaders zzbmLeaders = zxglOrganizeService.getZzbmLeaders(entitys.getZzbm());
                    entitys.setDepartmentManagerZzbm(zzbmLeaders.getDepartmentManagerZzbm());
                    entitys.setDepartmentHeadleaderZzbm(zzbmLeaders.getDepartmentHeadleaderZzbm());
                    // endregion

                    // region 子表赋值协作部门负责人和部门领导
                    ZXGL_XzbmLeaders xzbmLeaders = zxglOrganizeService.getXzbmLeaders(entitys.getXzbm());
                    entitys.setDepartmentManagerXzbm(xzbmLeaders.getDepartmentManagerXzbm());
                    entitys.setDepartmentHeadleaderXzbm(xzbmLeaders.getDepartmentHeadleaderXzbm());
                    // endregion
                    zXGL_XiangMuLiXiang_MingXiService.save(entitys);
                    //遍历部门信息，根据主责部门循环，创建明细内容
                    list.add(entitys);

                    // 验证主责部门是否为空
                    if (StringUtil.isNotEmpty(entitys.getZzbm())) {
                        flag = "1";
                    }
                }
                // endregion


                if ("1".equals(flag) && "1".equals(zXGL_LiXiangGuanLiCrForm.getSftj())) {

                    //过滤掉接收状态为拒绝的数据
                    Map<String, List<ZXGL_XiangMuLiXiang_MingXiEntity>> listMap = list
                            .stream().filter(t -> !"669883054189213317".equals(t.getJszt())).collect(Collectors.groupingBy(ZXGL_XiangMuLiXiang_MingXiEntity::getZzbm));

                    //遍历分组数据
                    for (Map.Entry<String, List<ZXGL_XiangMuLiXiang_MingXiEntity>> entry : listMap.entrySet()) {
                        log.info("entry:=============================>" + entry.getKey());
                        // entity 是保存使用
                        ZXGL_XMCFZGBMJSEntity zxgl_xmcfzgbmjsEntity = new ZXGL_XMCFZGBMJSEntity();
                        // form 是提交流程的时候使用
                        ZXGL_XMCFZGBMJSCrForm zXGL_XMCFZGBMJSCrForm = new ZXGL_XMCFZGBMJSCrForm();

                        String zhujianID = RandomUtil.uuId();
                        // 部门确认主键
                        zxgl_xmcfzgbmjsEntity.setId(zhujianID);

                        // 部门确认项目立项Id
                        zxgl_xmcfzgbmjsEntity.setXmlxdid(mainId);
                        // form 项目立项Id
                        zXGL_XMCFZGBMJSCrForm.setXmlxdid(mainId);

                        // region 主表赋值部门负责人和部门领导
                        zxgl_xmcfzgbmjsEntity.setDepartmentManagerZzbm(entry.getValue().get(0).getDepartmentManagerZzbm());
                        zxgl_xmcfzgbmjsEntity.setDepartmentHeadleaderZzbm(entry.getValue().get(0).getDepartmentHeadleaderZzbm());
                        // endregion


                        logger.info("部门信息：{}---->" + entry.getValue().get(0).getZzbm());

                        String managerId = organizeApi.getById(entry.getValue().get(0).getZzbm()).getManager();
                        logger.info("managerId:{}--->" + managerId);

                        String Id = organizeApi.getById(entry.getValue().get(0).getZzbm()).getId();
                        logger.info("Id:{}--->" + Id);

                        UserInfo userInfo = userProvider.get();


                        zxgl_xmcfzgbmjsEntity.setDepartmentName(entry.getValue().get(0).getZzbm());
                        zXGL_XMCFZGBMJSCrForm.setDepartmentName(entry.getValue().get(0).getZzbm());

                        zxgl_xmcfzgbmjsEntity.setOrganizeName(zXGL_LiXiangGuanLiCrForm.getOrganizeName());
                        zXGL_XMCFZGBMJSCrForm.setOrganizeName(zXGL_LiXiangGuanLiCrForm.getOrganizeName());

                        zxgl_xmcfzgbmjsEntity.setCreatorTime(entity.getCreatorTime());
                        zXGL_XMCFZGBMJSCrForm.setCreatorTime(entity.getCreatorTime().getTime());

                        zxgl_xmcfzgbmjsEntity.setLxwj(zXGL_LiXiangGuanLiCrForm.getScfj());
                        zXGL_XMCFZGBMJSCrForm.setLxwj(zXGL_LiXiangGuanLiCrForm.getScfj());

                        zxgl_xmcfzgbmjsEntity.setBt(zXGL_LiXiangGuanLiCrForm.getBt());
                        zXGL_XMCFZGBMJSCrForm.setBt(zXGL_LiXiangGuanLiCrForm.getBt());

                        //OrganizeEntity organizeEntity = organizeApi.getById(entity.getDepartmentName());
                        //需改为获取明细中主责部门id
                        OrganizeEntity organizeEntity = organizeApi.getById(entry.getValue().get(0).getZzbm());
                        logger.info("组织信息：{}------>" + JSON.toJSONString(organizeEntity));
                        zxgl_xmcfzgbmjsEntity.setZrr(organizeEntity.getDirector());
                        zXGL_XMCFZGBMJSCrForm.setZrr(organizeEntity.getDirector());
                        zXGL_XMCFZGBMJSService.save(zxgl_xmcfzgbmjsEntity);


                        List<ZXGL_XMCFZGBMJS_MingXiModel> zxgl_xmcfzgbmjs_mingXiEntityList = new ArrayList<>();
                        List<ZXGL_XMCFZGBMJS_MingXiEntity> zxgl_xmcfzgbmjs_mingXiEntityList1 = new ArrayList<>();
                        //操作
                        for (ZXGL_XiangMuLiXiang_MingXiEntity model : entry.getValue()) {

                            ZXGL_XMCFZGBMJS_MingXiModel zxgl_xmcfzgbmjs_mingXiModel = new ZXGL_XMCFZGBMJS_MingXiModel();
                            ZXGL_XMCFZGBMJS_MingXiEntity zxgl_xmcfzgbmjs_mingXiEntity = new ZXGL_XMCFZGBMJS_MingXiEntity();

                            zxgl_xmcfzgbmjs_mingXiEntity.setId(RandomUtil.uuId());
                            zxgl_xmcfzgbmjs_mingXiEntity.setMainid(zxgl_xmcfzgbmjsEntity.getId());
                            zxgl_xmcfzgbmjs_mingXiEntity.setCreatorTime(new Date());
                            // zxgl_xmcfzgbmjs_mingXiModel.setCreatorTime(System.currentTimeMillis());

                            zxgl_xmcfzgbmjs_mingXiEntity.setXmid(model.getId());

                            zxgl_xmcfzgbmjs_mingXiEntity.setXmmc(model.getXmmc());
                            zxgl_xmcfzgbmjs_mingXiModel.setXmmc(model.getXmmc());

                            zxgl_xmcfzgbmjs_mingXiEntity.setXmbh(model.getXmbh());
                            zxgl_xmcfzgbmjs_mingXiModel.setXmbh(model.getXmbh());

                            zxgl_xmcfzgbmjs_mingXiEntity.setXmlx(model.getXmlx());
                            zxgl_xmcfzgbmjs_mingXiModel.setXmlx(model.getXmlx());

                            zxgl_xmcfzgbmjs_mingXiEntity.setXmly(model.getXmly());
                            zxgl_xmcfzgbmjs_mingXiModel.setXmly(model.getXmly());

                            zxgl_xmcfzgbmjs_mingXiEntity.setJhksrq(model.getJhkssj());
                            if (model.getJhkssj() != null) {
                                zxgl_xmcfzgbmjs_mingXiModel.setJhksrq(model.getJhkssj().getTime());
                            }

                            zxgl_xmcfzgbmjs_mingXiEntity.setJhjsrq(model.getJhjssj());
                            if (model.getJhjssj() != null) {
                                zxgl_xmcfzgbmjs_mingXiModel.setJhjsrq(model.getJhjssj().getTime());
                            }

                            zxgl_xmcfzgbmjs_mingXiEntity.setZrbm(model.getZzbm());
                            zxgl_xmcfzgbmjs_mingXiModel.setZrbm(model.getZzbm());

                            zxgl_xmcfzgbmjs_mingXiEntity.setXzbm(model.getXzbm());
                            zxgl_xmcfzgbmjs_mingXiModel.setXzbm(model.getXzbm());

                            zxgl_xmcfzgbmjs_mingXiEntity.setMblx(model.getMblx());
                            zxgl_xmcfzgbmjs_mingXiModel.setMblx(model.getMblx());

                            zxgl_xmcfzgbmjs_mingXiEntity.setMbz(model.getMbz());
                            zxgl_xmcfzgbmjs_mingXiModel.setMbz(model.getMbz());

                            zxgl_xmcfzgbmjs_mingXiEntity.setGzmb(model.getGzmb());
                            zxgl_xmcfzgbmjs_mingXiModel.setGzmb(model.getGzmb());

                            zxgl_xmcfzgbmjs_mingXiEntity.setFkzq(model.getFkzq());
                            zxgl_xmcfzgbmjs_mingXiModel.setFkzq(model.getFkzq());

                            zxgl_xmcfzgbmjs_mingXiEntity.setMbzdw(model.getMbzdw());
                            zxgl_xmcfzgbmjs_mingXiModel.setMbzdw(model.getMbzdw());


                            zxgl_xmcfzgbmjs_mingXiEntityList.add(zxgl_xmcfzgbmjs_mingXiModel);

                            logger.info("项目分解到部门toJSONString:{}--------->" + zxgl_xmcfzgbmjs_mingXiEntity);
                            zxgl_xmcfzgbmjs_mingXiEntityList1.add(zxgl_xmcfzgbmjs_mingXiEntity);
                        }

                        logger.info("保存明细数据：{}----->" + zxgl_xmcfzgbmjs_mingXiEntityList1);
                        logger.info("zxgl_xmcfzgbmjs_mingXiEntityList:{}----->" + zxgl_xmcfzgbmjs_mingXiEntityList);

                        zXGL_XMCFZGBMJS_MingXiService.saveBatch(zxgl_xmcfzgbmjs_mingXiEntityList1);

                        zXGL_XMCFZGBMJSCrForm.setZxgl_xmcfzgbmjs_mingxiList(zxgl_xmcfzgbmjs_mingXiEntityList);
                        String visualId = "667650650904992965";
                        VisualdevEntity visualdevEntity = visualdevService.getInfo(visualId);

                        try {
                            VisualUtils.submitFlowTask(visualdevEntity, zhujianID, zXGL_XMCFZGBMJSCrForm, userInfo, zXGL_XMCFZGBMJSCrForm.getCandidateList());
                            FlowTaskEntity flowTaskEntity = flowTaskService.getInfo(zhujianID);
                            if (flowTaskEntity != null) {
                                flowTaskEntity.setTitle(zXGL_XMCFZGBMJSCrForm.getBt());
                                flowTaskService.update(flowTaskEntity);
                            }
                        } catch (WorkFlowException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return ActionResult.success("保存成功", entity.getId());
    }

    //第二种分组的方法
//    public static Map<String, List<ZXGL_XiangMuLiXiang_MingXiEntity>> groupingArrayListTwo(List<ZXGL_XiangMuLiXiang_MingXiEntity> list) {
//        //使用jdk8的流式编程对list集合进行分组
//        Map<String, List<ZXGL_XiangMuLiXiang_MingXiEntity>> listMap =
//                //过滤掉接收状态为拒绝的数据
//                list.stream().filter(t -> !"669883054189213317".equals(t.getJszt())).collect(Collectors.groupingBy(t -> t.getZzbm()));
//        return listMap;
//
//    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("查询立项管理信息")
    @GetMapping("/{id}")
    public ActionResult<ZXGL_LiXiangGuanLiInfoVO> info(@PathVariable("id") String id) {
        ZXGL_LiXiangGuanLiEntity entity = zXGL_LiXiangGuanLiService.getInfo(id);
        ZXGL_LiXiangGuanLiInfoVO vo = JsonUtil.getJsonToBean(entity, ZXGL_LiXiangGuanLiInfoVO.class);

        //子表
        List<ZXGL_XiangMuLiXiang_MingXiEntity> ZXGL_XiangMuLiXiang_MingXiList = zXGL_LiXiangGuanLiService.GetZXGL_XiangMuLiXiang_MingXiList(id);
        if (ZXGL_XiangMuLiXiang_MingXiList != null && ZXGL_XiangMuLiXiang_MingXiList.size() > 0) {
            for (ZXGL_XiangMuLiXiang_MingXiEntity zxgl_xiangmulixiang_mingxiEntity : ZXGL_XiangMuLiXiang_MingXiList) {

            }
            vo.setZXGL_XiangMuLiXiang_MingXiList(JsonUtil.getJsonToList(ZXGL_XiangMuLiXiang_MingXiList, ZXGL_XiangMuLiXiang_MingXiModel.class));
        }
        //处理明细返回前台null的一系列问题
        else {
            vo.setZXGL_XiangMuLiXiang_MingXiList(new ArrayList<>());
        }
        //副表
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("查询立项管理详情")
    @GetMapping("/detail/{id}")
    public ActionResult<ZXGL_LiXiangGuanLiInfoVO> detailInfo(@PathVariable("id") String id) {
        ZXGL_LiXiangGuanLiEntity entity = zXGL_LiXiangGuanLiService.getInfo(id);
        ZXGL_LiXiangGuanLiInfoVO vo = JsonUtil.getJsonToBean(entity, ZXGL_LiXiangGuanLiInfoVO.class);
        vo.setOrganizeName(generaterSwapUtil.comSelectValues(vo.getOrganizeName()));
        vo.setDepartmentName(generaterSwapUtil.comSelectValues(vo.getDepartmentName()));
        vo.setCreatorUser(generaterSwapUtil.userSelectValues(vo.getCreatorUser()));
        vo.setScfj(generaterSwapUtil.getFileNameInJson(vo.getScfj()));

        //子表数据转换
        List<ZXGL_XiangMuLiXiang_MingXiEntity> zXGL_XiangMuLiXiang_MingXiList = zXGL_LiXiangGuanLiService.GetZXGL_XiangMuLiXiang_MingXiList(id);
        if (zXGL_XiangMuLiXiang_MingXiList != null && zXGL_XiangMuLiXiang_MingXiList.size() > 0) {
            for (ZXGL_XiangMuLiXiang_MingXiEntity zXGL_XiangMuLiXiang_MingXiEntity : zXGL_XiangMuLiXiang_MingXiList) {
                zXGL_XiangMuLiXiang_MingXiEntity.setXmmc(zXGL_XiangMuLiXiang_MingXiEntity.getXmmc());
                zXGL_XiangMuLiXiang_MingXiEntity.setXmbh(zXGL_XiangMuLiXiang_MingXiEntity.getXmbh());
                zXGL_XiangMuLiXiang_MingXiEntity.setJhkssj(zXGL_XiangMuLiXiang_MingXiEntity.getJhkssj());
                zXGL_XiangMuLiXiang_MingXiEntity.setJhjssj(zXGL_XiangMuLiXiang_MingXiEntity.getJhjssj());

                zXGL_XiangMuLiXiang_MingXiEntity.setXmlx(dynDicUtil.getDicName(zXGL_XiangMuLiXiang_MingXiEntity.getXmlx(), "667277254828496197"));
                zXGL_XiangMuLiXiang_MingXiEntity.setXmly(dynDicUtil.getDicName(zXGL_XiangMuLiXiang_MingXiEntity.getXmly(), "667353988936504645"));
                zXGL_XiangMuLiXiang_MingXiEntity.setQtr(generaterSwapUtil.userSelectValues(zXGL_XiangMuLiXiang_MingXiEntity.getQtr()));
                zXGL_XiangMuLiXiang_MingXiEntity.setQtbm(generaterSwapUtil.comSelectValues(zXGL_XiangMuLiXiang_MingXiEntity.getQtbm()));
                zXGL_XiangMuLiXiang_MingXiEntity.setZzbm(generaterSwapUtil.comSelectValues(zXGL_XiangMuLiXiang_MingXiEntity.getZzbm()));
                zXGL_XiangMuLiXiang_MingXiEntity.setXzbm(generaterSwapUtil.comSelectValues(zXGL_XiangMuLiXiang_MingXiEntity.getXzbm()));
                zXGL_XiangMuLiXiang_MingXiEntity.setMblx(dynDicUtil.getDicName(zXGL_XiangMuLiXiang_MingXiEntity.getMblx(), "670160918163781253"));
                zXGL_XiangMuLiXiang_MingXiEntity.setFkpl(dynDicUtil.getDicName(zXGL_XiangMuLiXiang_MingXiEntity.getFkpl(), "667375897669539141"));
                zXGL_XiangMuLiXiang_MingXiEntity.setSjly(dynDicUtil.getDicName(zXGL_XiangMuLiXiang_MingXiEntity.getSjly(), "669875872030815877"));
                zXGL_XiangMuLiXiang_MingXiEntity.setJszt(dynDicUtil.getDicName(zXGL_XiangMuLiXiang_MingXiEntity.getJszt(), "669882974119949957"));
                zXGL_XiangMuLiXiang_MingXiEntity.setFkzq(dynDicUtil.getDicName(zXGL_XiangMuLiXiang_MingXiEntity.getFkzq(), "667375897669539141"));
                zXGL_XiangMuLiXiang_MingXiEntity.setZdxm(dynDicUtil.getDicName(zXGL_XiangMuLiXiang_MingXiEntity.getZdxm(), "669876395320571525"));
                zXGL_XiangMuLiXiang_MingXiEntity.setZt(dynDicUtil.getDicName(zXGL_XiangMuLiXiang_MingXiEntity.getZt(), "667276146122954053"));
            }
            vo.setZXGL_XiangMuLiXiang_MingXiList(JsonUtil.getJsonToList(zXGL_XiangMuLiXiang_MingXiList, ZXGL_XiangMuLiXiang_MingXiModel.class));
        }


        //附表数据转换
        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @return
     */
    @ApiOperation("更新立项管理信息")
    @PutMapping("/{id}")
    @Transactional
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid ZXGL_LiXiangGuanLiUpForm zXGL_LiXiangGuanLiUpForm) throws DataException {
        logger.info("进入更新方法中：{}----->");
        String jsonString = JSON.toJSONString(zXGL_LiXiangGuanLiUpForm);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        logger.info("项目立项更新数据：{}----------->" + jsonObject.toJSONString());
        //TODO 先删除数据，再重新新增：项目id为项目分解到部门xmlxdid
        logger.info("项目立项id：{}----------->" + id);
        List<ZXGL_XiangMuLiXiang_MingXiEntity> ZXGL_XiangMuLiXiang_MingXiList1 = JsonUtil.getJsonToList(zXGL_LiXiangGuanLiUpForm.getZxgl_xiangmulixiang_mingxiList(), ZXGL_XiangMuLiXiang_MingXiEntity.class);
        List<String> listXmid = new ArrayList<>();
        for (ZXGL_XiangMuLiXiang_MingXiEntity entitys : ZXGL_XiangMuLiXiang_MingXiList1) {
            listXmid.add(entitys.getId());
        }
        logger.info("项目分解到部门ids：{}---->" + listXmid.toString());
        //提交状态的情况下，删除项目分解到部门主表和明细表数据
        if ("1".equals(jsonObject.getString("sftj"))) {
//            zXGL_XMCFZGBMJS_MingXiService.deleteByXmid(listXmid);
//            zXGL_XMCFZGBMJSService.deleteByXmlxdid(id);
        }
//        UserInfo userInfo = userProvider.get();
        ZXGL_LiXiangGuanLiEntity entity = zXGL_LiXiangGuanLiService.getInfo(id);
        if (entity != null) {
            ZXGL_LiXiangGuanLiEntity subentity = JsonUtil.getJsonToBean(zXGL_LiXiangGuanLiUpForm, ZXGL_LiXiangGuanLiEntity.class);
            // region 主表赋值部门负责人和部门领导
            ZXGL_Leaders leaders = zxglOrganizeService.getLeaders();
            subentity.setDepartmentManager(leaders.getDepartmentManager());
            subentity.setDepartmentHeadleader(leaders.getDepartmentHeadleader());
            // endregion
            zXGL_LiXiangGuanLiService.update(id, subentity);
            QueryWrapper<ZXGL_XiangMuLiXiang_MingXiEntity> ZXGL_XiangMuLiXiang_MingXiqueryWrapper = new QueryWrapper<>();
            ZXGL_XiangMuLiXiang_MingXiqueryWrapper.lambda().eq(ZXGL_XiangMuLiXiang_MingXiEntity::getMainid, entity.getId());
            zXGL_XiangMuLiXiang_MingXiService.remove(ZXGL_XiangMuLiXiang_MingXiqueryWrapper);

            List<ZXGL_XiangMuLiXiang_MingXiEntity> ZXGL_XiangMuLiXiang_MingXiList = JsonUtil.getJsonToList(zXGL_LiXiangGuanLiUpForm.getZxgl_xiangmulixiang_mingxiList(), ZXGL_XiangMuLiXiang_MingXiEntity.class);

            Map<String, List<ZXGL_XiangMuLiXiang_MingXiEntity>> map2 = new HashMap<>();

            List<ZXGL_XMCFZGBMJS_MingXiModel> zxgl_xmcfzgbmjs_mingXiEntityList = new ArrayList<>();

            List<ZXGL_XiangMuLiXiang_MingXiEntity> list = new ArrayList<>();
            int jjxms = 0;
            for (ZXGL_XiangMuLiXiang_MingXiEntity entitys : ZXGL_XiangMuLiXiang_MingXiList) {
                //更新项目分解到部门：
                entitys.setId(RandomUtil.uuId());
                entitys.setMainid(entity.getId());
                entitys.setCreatorTime(new Date());

                // region 子表赋值部门负责人和部门领导
                entitys.setDepartmentManager(leaders.getDepartmentManager());
                entitys.setDepartmentHeadleader(leaders.getDepartmentHeadleader());
                // endregion

                // region 子表赋值主责部门负责人和部门领导
                ZXGL_ZzbmLeaders zzbmLeaders = zxglOrganizeService.getZzbmLeaders(entitys.getZzbm());
                entitys.setDepartmentManagerZzbm(zzbmLeaders.getDepartmentManagerZzbm());
                entitys.setDepartmentHeadleaderZzbm(zzbmLeaders.getDepartmentHeadleaderZzbm());
                // endregion

                // region 子表赋值协作部门负责人和部门领导
                ZXGL_XzbmLeaders xzbmLeaders = zxglOrganizeService.getXzbmLeaders(entitys.getXzbm());
                entitys.setDepartmentManagerXzbm(xzbmLeaders.getDepartmentManagerXzbm());
                entitys.setDepartmentHeadleaderXzbm(xzbmLeaders.getDepartmentHeadleaderXzbm());
                // endregion

                //如果接收状态为拒绝 669883022308308613。则赋空值，解决提交后，还能编辑的问题
                if ("669883022308308613".equals(entitys.getJszt()) && "1".equals(zXGL_LiXiangGuanLiUpForm.getSftj())) {
                    entitys.setJszt("");
                    jjxms++;
                }
                logger.info("ZXGL_XiangMuLiXiang_MingXiList：{}---->" + ZXGL_XiangMuLiXiang_MingXiList.toString());
                logger.info("项目立项明细id：{}----->" + entitys.getId());
                logger.info("项目立项项目id：{}-------->" + entitys.getXmid());
                //把立项管理明细的内容取到：
                //遍历部门信息，根据主责部门循环，
                list.add(entitys);
                zXGL_XiangMuLiXiang_MingXiService.save(entitys);
            }
            //拒绝项目数大于0，则待确认项目加上拒绝项目树，并更新主表
            if (jjxms > 0 && "1".equals(jsonObject.getString("sftj"))) {
                subentity.setDqrxms(entity.getDqrxms() + jjxms);
                subentity.setJjxms(0);
                zXGL_LiXiangGuanLiService.update(id, subentity);
            }

            String flag = "";
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode rootNode = objectMapper.readTree(jsonObject.toJSONString());
                JsonNode listNode = rootNode.get("zxgl_xiangmulixiang_mingxiList");
                if (listNode != null && listNode.isArray()) {
                    for (JsonNode item : listNode) {
                        if (item.has("zzbm")) {
                            flag = "1";
                            logger.info("存在 'zzbm' 字段");
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            logger.info("不存在 'zzbm' 字段");

            if ("1".equals(flag) && "1".equals(jsonObject.getString("sftj"))) {
                map2 = ZXGL_XiangMuLiXiang_MingXiList
                        .stream().filter(t -> !"669883054189213317".equals(t.getJszt())).collect(Collectors.groupingBy(ZXGL_XiangMuLiXiang_MingXiEntity::getZzbm));
                //遍历分组后的map2
                for (String s : map2.keySet()) {
                    logger.info("更新分组之后：{}---->" + map2.get(s));
                    logger.info("更新分组之后个数：{}---->" + map2.get(s).size());
                    ZXGL_XMCFZGBMJSCrForm zXGL_XMCFZGBMJSCrForm = new ZXGL_XMCFZGBMJSCrForm();
                    ZXGL_XMCFZGBMJSEntity zxgl_xmcfzgbmjsEntity = new ZXGL_XMCFZGBMJSEntity();
                    String zhujianID = RandomUtil.uuId();
                    zxgl_xmcfzgbmjsEntity.setId(zhujianID);
                    zxgl_xmcfzgbmjsEntity.setXmlxdid(zXGL_LiXiangGuanLiUpForm.getId());

                    // region 主表赋值部门负责人和部门领导
                    zxgl_xmcfzgbmjsEntity.setDepartmentManagerZzbm(map2.get(s).get(0).getDepartmentManagerZzbm());
                    zxgl_xmcfzgbmjsEntity.setDepartmentHeadleaderZzbm(map2.get(s).get(0).getDepartmentHeadleaderZzbm());
                    // endregion


                    zxgl_xmcfzgbmjsEntity.setDepartmentName(map2.get(s).get(0).getZzbm());
                    zxgl_xmcfzgbmjsEntity.setOrganizeName(entity.getOrganizeName());
                    //根据主责部门找到主责人
                    logger.info("主责部门---->" + map2.get(s).get(0).getZzbm());
                    logger.info("部门负责人：{}---->" + organizeApi.getById(map2.get(s).get(0).getZzbm()).getDirector());
                    zxgl_xmcfzgbmjsEntity.setZrr(organizeApi.getById(map2.get(s).get(0).getZzbm()).getDirector());
                    zxgl_xmcfzgbmjsEntity.setCreatorTime(entity.getCreatorTime());
                    zxgl_xmcfzgbmjsEntity.setLxwj(zXGL_LiXiangGuanLiUpForm.getScfj());

                    zxgl_xmcfzgbmjsEntity.setBt(zXGL_LiXiangGuanLiUpForm.getBt());


                    zXGL_XMCFZGBMJSCrForm.setXmlxdid(zXGL_LiXiangGuanLiUpForm.getId());
                    logger.info("部门信息：{}---->" + map2.get(s).get(0).getZzbm());

                    zXGL_XMCFZGBMJSCrForm.setDepartmentName(map2.get(s).get(0).getZzbm());
                    zXGL_XMCFZGBMJSCrForm.setOrganizeName(entity.getOrganizeName());
                    zXGL_XMCFZGBMJSCrForm.setZrr(organizeApi.getById(map2.get(s).get(0).getZzbm()).getDirector());
                    zXGL_XMCFZGBMJSCrForm.setCreatorTime(entity.getCreatorTime().getTime());
                    zXGL_XMCFZGBMJSCrForm.setLxwj(zXGL_LiXiangGuanLiUpForm.getScfj());
                    zXGL_XMCFZGBMJSCrForm.setBt(zXGL_LiXiangGuanLiUpForm.getBt());

                    logger.info("zXGL_XMCFZGBMJSCrForm:{}----->" + JSON.toJSONString(zXGL_XMCFZGBMJSCrForm));
                    logger.info("entity:{}----->" + JSON.toJSONString(entity));
                    logger.info("zxgl_xmcfzgbmjsEntity:{}----->" + JSON.toJSONString(zxgl_xmcfzgbmjsEntity));

                    zXGL_XMCFZGBMJSService.save(zxgl_xmcfzgbmjsEntity);

                    String managerId = organizeApi.getById(map2.get(s).get(0).getZzbm()).getDirector();
                    logger.info("managerId:{}--->" + managerId);

                    String Id = organizeApi.getById(map2.get(s).get(0).getZzbm()).getId();
                    logger.info("Id:{}--->" + Id);

                    UserInfo userInfo = userProvider.get();

                    //操作
                    for (int i = 0; i < map2.get(s).size(); i++) {
                        ZXGL_XMCFZGBMJS_MingXiEntity zxgl_xmcfzgbmjs_mingXiEntity = new ZXGL_XMCFZGBMJS_MingXiEntity();
                        zxgl_xmcfzgbmjs_mingXiEntity.setId(RandomUtil.uuId());
                        zxgl_xmcfzgbmjs_mingXiEntity.setMainid(zxgl_xmcfzgbmjsEntity.getId());

                        zxgl_xmcfzgbmjs_mingXiEntity.setXmid(map2.get(s).get(i).getId());
                        zxgl_xmcfzgbmjs_mingXiEntity.setXmmc(map2.get(s).get(i).getXmmc());
                        zxgl_xmcfzgbmjs_mingXiEntity.setXmbh(map2.get(s).get(i).getXmbh());
                        zxgl_xmcfzgbmjs_mingXiEntity.setXmlx(map2.get(s).get(i).getXmlx());
                        zxgl_xmcfzgbmjs_mingXiEntity.setXmly(map2.get(s).get(i).getXmly());
                        zxgl_xmcfzgbmjs_mingXiEntity.setJhksrq(map2.get(s).get(i).getJhkssj());
                        zxgl_xmcfzgbmjs_mingXiEntity.setJhjsrq(map2.get(s).get(i).getJhjssj());
                        zxgl_xmcfzgbmjs_mingXiEntity.setZrbm(map2.get(s).get(i).getZzbm());
                        zxgl_xmcfzgbmjs_mingXiEntity.setXzbm(map2.get(s).get(i).getXzbm());
                        zxgl_xmcfzgbmjs_mingXiEntity.setMblx(map2.get(s).get(i).getMblx());
                        zxgl_xmcfzgbmjs_mingXiEntity.setMbz(map2.get(s).get(i).getMbz());
                        zxgl_xmcfzgbmjs_mingXiEntity.setGzmb(map2.get(s).get(i).getGzmb());
                        zxgl_xmcfzgbmjs_mingXiEntity.setFkzq(map2.get(s).get(i).getFkzq());
                        zxgl_xmcfzgbmjs_mingXiEntity.setMbzdw(map2.get(s).get(i).getMbzdw());


                        ZXGL_XMCFZGBMJS_MingXiModel zxgl_xmcfzgbmjs_mingXiModel = new ZXGL_XMCFZGBMJS_MingXiModel();

                        zxgl_xmcfzgbmjs_mingXiModel.setXmmc(map2.get(s).get(i).getXmmc());
                        zxgl_xmcfzgbmjs_mingXiModel.setXmbh(map2.get(s).get(i).getXmbh());
                        zxgl_xmcfzgbmjs_mingXiModel.setXmlx(map2.get(s).get(i).getXmlx());
                        zxgl_xmcfzgbmjs_mingXiModel.setXmly(map2.get(s).get(i).getXmly());
                        if (map2.get(s).get(i).getJhkssj() != null) {
                            zxgl_xmcfzgbmjs_mingXiModel.setJhksrq(map2.get(s).get(i).getJhkssj().getTime());
                        }
                        if (map2.get(s).get(i).getJhjssj() != null) {
                            zxgl_xmcfzgbmjs_mingXiModel.setJhjsrq(map2.get(s).get(i).getJhjssj().getTime());
                        }
                        zxgl_xmcfzgbmjs_mingXiModel.setZrbm(map2.get(s).get(i).getZzbm());
                        zxgl_xmcfzgbmjs_mingXiModel.setXzbm(map2.get(s).get(i).getXzbm());
                        zxgl_xmcfzgbmjs_mingXiModel.setMblx(map2.get(s).get(i).getMblx());
                        zxgl_xmcfzgbmjs_mingXiModel.setMbz(map2.get(s).get(i).getMbz());
                        zxgl_xmcfzgbmjs_mingXiModel.setGzmb(map2.get(s).get(i).getGzmb());
                        zxgl_xmcfzgbmjs_mingXiModel.setFkzq(map2.get(s).get(i).getFkzq());
                        zxgl_xmcfzgbmjs_mingXiModel.setMbzdw(map2.get(s).get(i).getMbzdw());

                        zxgl_xmcfzgbmjs_mingXiEntityList.add(zxgl_xmcfzgbmjs_mingXiModel);

                        zxgl_xmcfzgbmjs_mingXiEntity.setCreatorTime(new Date());
                        zXGL_XMCFZGBMJS_MingXiService.save(zxgl_xmcfzgbmjs_mingXiEntity);
                    }

                    zXGL_XMCFZGBMJSCrForm.setZxgl_xmcfzgbmjs_mingxiList(zxgl_xmcfzgbmjs_mingXiEntityList);
                    String visualId = "667650650904992965";
                    VisualdevEntity visualdevEntity = visualdevService.getInfo(visualId);
                    logger.info("最终传递参数zXGL_XMCFZGBMJSCrForm:{}----->" + JSON.toJSONString(zXGL_XMCFZGBMJSCrForm));
                    try {
                        VisualUtils.submitFlowTask(visualdevEntity, zhujianID, zXGL_XMCFZGBMJSCrForm, userInfo, zXGL_XMCFZGBMJSCrForm.getCandidateList());
                        FlowTaskEntity flowTaskEntity = flowTaskService.getInfo(zhujianID);
                        if (flowTaskEntity != null) {
                            flowTaskEntity.setTitle(zXGL_XMCFZGBMJSCrForm.getBt());
                            flowTaskService.update(flowTaskEntity);
                        }
                    } catch (WorkFlowException e) {
                        e.printStackTrace();
                    }
                }
            }

            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除立项管理信息")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ZXGL_LiXiangGuanLiEntity entity = zXGL_LiXiangGuanLiService.getInfo(id);
        if (entity != null) {
            zXGL_LiXiangGuanLiService.delete(entity);
            QueryWrapper<ZXGL_XiangMuLiXiang_MingXiEntity> queryWrapperZXGL_XiangMuLiXiang_MingXi = new QueryWrapper<>();
            queryWrapperZXGL_XiangMuLiXiang_MingXi.lambda().eq(ZXGL_XiangMuLiXiang_MingXiEntity::getMainid, entity.getId());
            zXGL_XiangMuLiXiang_MingXiService.remove(queryWrapperZXGL_XiangMuLiXiang_MingXi);

        }
        return ActionResult.success("删除成功");
    }


    /**
     * @param file:
     * @Description:上传附件解析数据
     * @Author: ZhaoChenXu
     * @Date: 2025-03-24 16:02
     * @return: org.springframework.http.ResponseEntity<java.lang.Object>
     **/
    @ApiOperation("上传附件解析数据")
    @PostMapping("/uploadExcel")
    public ActionResult uploadExcel(@RequestParam("file") MultipartFile file) {
        try {
            logger.info("进入uploadExcel中：{}");
            // 解析Excel文件并处理数据
            List<Map<String, Object>> dataList = zXGL_LiXiangGuanLiService.parseExcelByEasyExcel(file);
            logger.info("dataListExcel数据组装：{}---------->" + dataList.toString());
            //解析数据插入明细表，并返回成功或者失败
            //循环list 从第二行开始传递
            List<ZXGL_XiangMuLiXiang_MingXiModel> zxgl_xiangMuLiXiang_mingXiModelList = new ArrayList<>();
            List<Map<String, Object>> mapList = new ArrayList<>();

            //分类id
            String parentid = "667274065077081413";
            List<Map<String, String>> dictionaryData = zXGL_LiXiangGuanLiService.getDictionaryData(parentid);

            for (int i = 0; i < dataList.size(); i++) {
                Map<String, Object> objectMap = new HashMap<>();
                Map<String, Object> excel_rowData = dataList.get(i);
                //项目名称
                objectMap.put("xmmc", dataList.get(i).get("项目名称"));
                //项目类型
                objectMap.put("xmlx", StringUtils.isNotBlank((String) excel_rowData.get("项目类型")) ? zXGL_LiXiangGuanLiService.getFIdByFullName(parentid, (String) excel_rowData.get("项目类型")) : "");
                //项目来源
                objectMap.put("xmly", StringUtils.isNotBlank((String) excel_rowData.get("项目来源")) ? zXGL_LiXiangGuanLiService.getFIdByFullName(parentid, (String) excel_rowData.get("项目来源")) : "");
                //计划开始日期
                long jhksrq_timestamp = StringUtils.isNotBlank((String) excel_rowData.get("计划开始日期")) ? DateConvertertUtil.convertDateToTimestamp((String) excel_rowData.get("计划开始日期"), "yyyy/M/d", true) : System.currentTimeMillis();
                objectMap.put("jhkssj", jhksrq_timestamp);
                //计划完成日期
                long timestampJhjssj = StringUtils.isNotBlank((String) excel_rowData.get("计划完成日期")) ? DateConvertertUtil.convertDateToTimestamp((String) excel_rowData.get("计划完成日期"), "yyyy/M/d", true) : System.currentTimeMillis();
                objectMap.put("jhjssj", timestampJhjssj);
                //目标类型
                objectMap.put("mblx", StringUtils.isNotBlank((String) excel_rowData.get("目标类型")) ? zXGL_LiXiangGuanLiService.getFIdByFullName(parentid, (String) excel_rowData.get("目标类型")) : "");
                //单位
                objectMap.put("mbzdw", StringUtils.isNotBlank((String) excel_rowData.get("单位")) ? zXGL_LiXiangGuanLiService.getFIdByFullName(parentid, (String) excel_rowData.get("单位").toString()) : "");
                //目标值
                objectMap.put("mbz", dataList.get(i).get("目标值"));
                //项目目标
                objectMap.put("gzmb", dataList.get(i).get("项目目标"));
                //反馈周期
                objectMap.put("fkzq", StringUtils.isNotBlank(excel_rowData.get("反馈周期").toString()) ? zXGL_LiXiangGuanLiService.getFIdByFullName(parentid, excel_rowData.get("反馈周期").toString()) : "");
                //重点项目
                objectMap.put("zdxm", StringUtils.isNotBlank(excel_rowData.get("重点项目").toString()) ? zXGL_LiXiangGuanLiService.getFIdByFullName(parentid, excel_rowData.get("重点项目").toString()) : "");
                //数据来源 固定值，excel导入
                objectMap.put("sjly", "669876626774849157");


                mapList.add(objectMap);
            }
            logger.info("返回给前端的数据：{}------------->" + mapList.toString());
            // 将数据转换为JSON格式返回
            return ActionResult.success(mapList);
        } catch (Exception e) {
            e.printStackTrace();
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing the file");
            return ActionResult.fail("Error processing the file");
        }
    }


    /**
     * @param :
     * @Description:项目名称验重
     * @Author: ZhaoChenXu
     * @Date: 2025-03-14 17:30
     * @return: jnpf.base.ActionResult
     **/
    @ApiOperation("项目名称验重")
    @PostMapping("/checkProjectName")
    public ActionResult checkProjectName(@RequestBody @Valid ZXGL_LiXiangGuanLiUpForm zXGL_LiXiangGuanLiUpForm) {
        logger.info("zXGL_LiXiangGuanLiUpForm:{}----->" + JSON.toJSONString(zXGL_LiXiangGuanLiUpForm));
        if (zXGL_LiXiangGuanLiUpForm.getZxgl_xiangmulixiang_mingxiList().size() == 0) {
            logger.info("说明没有查到数据：{}---->");
            List list = new ArrayList();
            return ActionResult.success(list);
        } else {
            List list = new ArrayList();
            for (int i = 0; i < zXGL_LiXiangGuanLiUpForm.getZxgl_xiangmulixiang_mingxiList().size(); i++) {
                List<String> xmmc = zXGL_LiXiangGuanLiService.findByName(zXGL_LiXiangGuanLiUpForm.getZxgl_xiangmulixiang_mingxiList().get(i).getXmmc(), zXGL_LiXiangGuanLiUpForm.getId());
                logger.info("xmmc:{}------>" + xmmc.toString());
                if (xmmc.size() == 0) {
                    continue;
                } else {
                    list.add(xmmc.get(0));
                }
            }

            return ActionResult.success(list);
        }
    }


    /**
     * @Description:获取用户信息
     * @Author: ZhaoChenXu
     * @Date: 2025-03-14 13:42
     * @return: jnpf.base.UserInfo
     **/
    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    public ActionResult<UserInfoVO> getUserInfo() {
        UserInfo userInfo = userProvider.get();
        UserInfoVO vo = JsonUtil.getJsonToBean(userInfo, UserInfoVO.class);
        logger.info("用户信息：{}----->" + userInfo.toString());

        return ActionResult.success(vo);
    }


    /**
     * @param zxgl_liXiangGuanLiDepResult:
     * @Description: 匹配部门回传
     * @Author: ZhaoChenXu
     * @Date: 2025-03-19 11:59
     * @return: org.springframework.http.ResponseEntity<java.lang.Object>
     **/
    @ApiOperation("匹配部门回传")
    @PostMapping("/matchDepartment")
    public ActionResult matchDepartment(@RequestBody ZXGL_LiXiangGuanLiDepResult zxgl_liXiangGuanLiDepResult) {
        String jsonString = JSON.toJSONString(zxgl_liXiangGuanLiDepResult);
        JSONObject jsonObjectResult = JSONObject.parseObject(jsonString);
        logger.info("获取回传分配部门数据：{}---------->" + jsonObjectResult.toJSONString());
        //解析数据，并返回
        if (jsonObjectResult.getBoolean("success")) {
            logger.info("返回成功");
            // 读取项目明细表
            List<ZXGL_XiangMuLiXiang_MingXiEntity> zxglXiangMuLiXiangMingXiEntities = zXGL_LiXiangGuanLiService.GetZXGL_XiangMuLiXiang_MingXiList(zxgl_liXiangGuanLiDepResult.getFlowId());
            List<ZXGL_XiangMuLiXiang_MingXiEntity> updateList = new ArrayList<>();
            logger.info("项目立项明细表内容：{}--->" + JSON.toJSONString(zxglXiangMuLiXiangMingXiEntities));

            for (ZXGL_XiangMuLiXiang_MingXiEntity entitys : zxglXiangMuLiXiangMingXiEntities) {
                for (int i = 0; i < zxgl_liXiangGuanLiDepResult.getZxgl_liXiangGuanLiReturnJsons().size(); i++) {
                    //如果数据库中项目名称 和 返回项目名称相同，则分配部门
                    if (entitys.getXmmc().equals(zxgl_liXiangGuanLiDepResult.getZxgl_liXiangGuanLiReturnJsons().get(i).getProjectName())) {
                        entitys.setZzbm("");
                        entitys.setXzbm("");
                        break;
                    }
                }
                zXGL_XiangMuLiXiang_MingXiService.updateById(entitys);
            }
            return ActionResult.success("返回成功");
        } else {
            return ActionResult.fail("返回失败");
        }
    }

    /**
     * @param
     * @Description:接受会议纪要，创建立项单
     * @Author: ZhaoChenXu
     * @Date: 2025-03-26 11:25
     * @return: jnpf.base.ActionResult
     **/
    @ApiOperation("接受会议纪要，创建立项单")
    @PostMapping("/outmeetingfilerecv")
    public ActionResult createLiXiangGuanLi(@RequestParam("scfj") MultipartFile file,
                                            @RequestParam("bt") String bt,
                                            @RequestParam("organize_name") String organize_name,
                                            @RequestParam("department_name") String department_name,
                                            @RequestParam("creator_user") String creator_user,
                                            @RequestParam("creator_time") Long creator_time,
                                            @RequestParam("sftj") String sftj) {

        logger.info("会议纪要接收请求数据：{file}------>" + file + "{bt}---->" + bt + "{organize_name}------>" + organize_name + "{department_name}----->" + department_name + "{creator_user}---->" + creator_user + "{creator_time}---->" + creator_time + "{sftj}---->" + sftj);
        ZXGL_LiXiangGuanLiEntity entity = new ZXGL_LiXiangGuanLiEntity();
        String mainId = RandomUtil.uuId();
        entity.setId(mainId);
        //标题
        entity.setBt(bt);
        //组织名称
        entity.setOrganizeName(organize_name);
        //部门名称
        entity.setDepartmentName(department_name);

        //创建时间
        Date date = new Date(creator_time);

        logger.info("date:{}----->" + date);
        entity.setCreatorTime(date);
        //是否已提交
        entity.setSftj(sftj);
        //TODO 会议纪要
        FileApi fileApi = SpringContext.getBean(FileApi.class);

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        // 格式化日期
        String formattedDate = currentDate.format(formatter);
        String fileName = formattedDate + "_" + RandomUtil.uuId() + FileNameUtils.getExtension(file.getOriginalFilename());
        logger.info("fileName:{}------>" + fileName);
        String path = fileApi.getPath(FileTypeEnum.ANNEX) + fileName;
        logger.info("path:{}------>" + path);

        //判断是否oss
        try {
            log.info("new String(file.getBytes()):========================>" + file.getBytes());
            // fileUploadProvider.uploadFiles(new UploadFileModel(FileTypeEnum.ANNEX.toLowerCase(), fileName, path, file.getBytes()));
            fileUploadUtil.uploadFile(file, fileName);
            logger.info("path:{}------>上传成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        logger.info("-----------文件上传成功之后：{}----->");

        List listUploader = new ArrayList();
        JSONObject jsonObjectUploader = new JSONObject();
        jsonObjectUploader.put("name", file.getOriginalFilename());
        jsonObjectUploader.put("fileId", fileName);
        jsonObjectUploader.put("fileVersionId", "");

        String newString = UploaderUtil.uploaderFile(fileName + "#" + "Annex").replace("?", "/");
        jsonObjectUploader.put("url", newString);
        listUploader.add(jsonObjectUploader);

        logger.info("listUploader：{}------>" + JSON.toJSONString(listUploader));
        entity.setScfj(JSON.toJSONString(listUploader));


        UserEntity userEntity = userService.getInfo(creator_user);
        if (userEntity == null) {
            return ActionResult.fail("用户不存在");
        }
        UserInfo userInfo = userService.copyFromEntity(userEntity);
        entity.setOrganizeId(userInfo.getOrganizeId());
        entity.setOrganizeName(userInfo.getOrganizeName());
        entity.setCompanyId(userInfo.getCompanyId());
        entity.setCompanyName(userInfo.getCompanyName());
        entity.setDepartmentId(userInfo.getDepartmentId());
        entity.setDepartmentName(userInfo.getDepartmentName());
        //创建人
        entity.setCreatorUser(userEntity.getRealName());
        entity.setCreatorUserId(creator_user);
        // 最后修改人
        entity.setLastModifyUserId(creator_user);
        entity.setLastModifyUser(userEntity.getRealName());

        Boolean save = zXGL_LiXiangGuanLiService.saveLiXiangGuanLi(entity);
        if (save) {
            return ActionResult.success();
        } else {
            return ActionResult.fail("false");
        }

    }

    public static String getFileExtension(String fileName) {
        if (fileName == null) {
            return null;
        }
        int lastIndex = fileName.lastIndexOf('.');
        if (lastIndex == -1 || lastIndex == fileName.length() - 1) {
            return "";
        }
        return fileName.substring(lastIndex);
    }

    @ApiOperation("解析人员信息")
    @PostMapping("/matchPerson")
    public ActionResult matchPerson(@RequestBody ZXGL_LiXiangGuanLiPersonResult zxgl_liXiangGuanLiPersonResult) {
        String jsonString = JSON.toJSONString(zxgl_liXiangGuanLiPersonResult);
        JSONObject jsonObjectResult = JSONObject.parseObject(jsonString);
        logger.info("获取回传分配人员数据：{}---------->" + jsonObjectResult.toJSONString());
        //解析数据，并返回
        if (jsonObjectResult.getBoolean("success")) {
            logger.info("返回成功");
            //插入到相关明细表

            return ActionResult.success("返回成功");
        } else {
            return ActionResult.fail("返回失败");
        }
    }


    /**
     * 获取项目明细目标值
     *
     * @param id
     * @return
     */
    @ApiOperation("获取项目明细目标值")
    @GetMapping("/mingximbz/{id}")
    public ActionResult mingxi(@PathVariable("id") String id) {
        ZXGL_XiangMuLiXiang_MingXiEntity entity = zXGL_XiangMuLiXiang_MingXiService.getInfo(id);
        if (entity != null) {
            return ActionResult.success(entity.getMbz());
        } else {
            return ActionResult.success(0);
        }
    }

    @ApiOperation("下载模板")
    @GetMapping("/download")
    public ResponseEntity<Resource> download() throws IOException {
        log.info("进入方法");
        // 从resources目录读取文件
        ClassPathResource file = new ClassPathResource("execl/template.xlsx");
        log.info(file.getFilename());
        // 2. 设置响应头（关键：指定 MIME 类型）
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + URLEncoder.encode(file.getFilename(), "UTF-8") + "\"")
                .body(file);
    }
}
